/**
 * 
 */
package com.haisen.lee.serviceimpl;

import java.net.URL;
import java.util.Map;

import org.cyberneko.html.parsers.DOMParser;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.haisen.lee.domain.FormDictionary;
import com.haisen.lee.service.IDomParser;
import com.haisen.lee.service.IDomParserThread;
import com.haisen.lee.util.DOMParserType;
import com.haisen.lee.util.DomTypeToThreadUtil;

/**
 * @author Haisen Lee
 * 
 */
public class HtmlDomParserImpl implements IDomParser {

	private static final DOMParserType selfDomParser = DOMParserType.HTML;
	private URL url;
	private DOMParser parser = null;
	private NamedNodeMap htmlAttributes = null;

	/**
	 * 
	 */
	public HtmlDomParserImpl() {
		this.init();
	}

	public void init() {

	}

	public void contentExtractor(Node root) {
		this.htmlAttributes = root.getAttributes();
		// TODO parser charset

		NodeList nodeList = root.getChildNodes();
		for (int i = 0; i < nodeList.getLength(); i++) {
			Node node = nodeList.item(i);
			String nodeName = node.getNodeName().toUpperCase();
			Map<String, DOMParserType> dealDomParserMap = selfDomParser
					.getDealDOMParserType();
			if (dealDomParserMap.containsKey(nodeName)) {
				// generate thread related to node name
				try {
					IDomParserThread htmlChildThread = DomTypeToThreadUtil
							.getInstance().getDomTypeToThreadDictionary().get(
									dealDomParserMap.get(nodeName))
							.newInstance();
					htmlChildThread.setUrl(url);
					Thread domParserThread = new Thread(htmlChildThread);
					domParserThread.start();
				} catch (InstantiationException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
			}
		}

	}

	public DOMParser getParser() {
		return parser;
	}

	public void setParser(DOMParser parser) {
		this.parser = parser;
	}

	public NamedNodeMap getHtmlAttributes() {
		return htmlAttributes;
	}

	public void setHtmlAttributes(NamedNodeMap htmlAttributes) {
		this.htmlAttributes = htmlAttributes;
	}

	@Override
	public void setUrl(URL url) {
		this.url = url;
	}
	
	@Override
	public String toString() {
		return "selfDomParserType : " + selfDomParser + "\t" + "url : " + url;
	}

	@Override
	public void setFormDictionary(FormDictionary formDictionary) {
		// TODO Auto-generated method stub
		
	}

}
